package 实验八;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class loginframe extends JFrame {
    private JTextField username;
    private JPasswordField password;
    private JButton login,register;
    public loginframe() {
        super();
        this.setSize(300,200);
        this.setTitle("Login");
        this.setLocationRelativeTo(getOwner());//居中

        //设置组合布局———3行2列表格
        Container cont=getContentPane();
        cont.setLayout(new GridLayout(3,2));

        //添加“用户名”、“密码”
        cont.add(new JLabel("username"));
        username=new JTextField(10);
        cont.add(username);
        cont.add(new JLabel("password"));
        password =new JPasswordField(10);
        cont.add(password);

        //添加“登录”、“注册”按钮
        login=new JButton(new ImageIcon("ico\\enter.gif"));
        register=new JButton (new ImageIcon("ico\\register.gif"));
        cont.add(login);
        cont.add(register);

        //注册监听器
        login.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                String pass =new String(password.getPassword());
                if(authenticateUser(username.getText(), pass)) {
                    personselect hello=new personselect();
                    hello.setVisible(true);
                    dispose();
                }
                else {
                    JOptionPane.showMessageDialog(null, "你输入的密码没有通过验证");
                }
            }
        });
    }
    private boolean authenticateUser(String username, String password) {
        try {
            // 连接数据库
            Connection connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;DatabaseName=pay202220336;trustServerCertificate=true;", "sa", "123456");

            // 查询数据库中是否存在匹配的用户名和密码
            String query = "SELECT * FROM users WHERE Uname = ? AND Upwd = ?";
            try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
                preparedStatement.setString(1, username);
                preparedStatement.setString(2, password);

                ResultSet resultSet = preparedStatement.executeQuery();

                // 如果查询结果非空，说明用户名和密码匹配成功
                if (resultSet.next()) {
                    // 显示登录成功的信息窗口
                    JOptionPane.showMessageDialog(null, "登录成功！");
                    return true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static void main(String[] args) {
        loginframe w=new loginframe();
        w.setVisible(true);
    }
}
